/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GeneracionEntrada.java
 *
 * Created on 19-jun-2011, 1:01:55
 */
package guiBoleteria;

import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import logica.Fabrica;
import logica.IBoleteria;
import util.datatypes.DTEntrada;
import util.datatypes.DTReserva;
import util.datatypes.DTTiposEntrada;
import util.datatypes.DTVenta;

/**
 *
 * @author Administrador
 */
public class GenerarEntrada extends javax.swing.JFrame {

    private DTReserva reserva;
    public GenerarEntrada() {
        initComponents();
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    }
    
    public GenerarEntrada(DTReserva r) {
        initComponents();
        reserva = r;
        txtPrecioTotal.setText(String.valueOf(r.getCostoTotal()));
        this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        PanelTitulo = new javax.swing.JPanel();
        lblVenta = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        PanelContenido = new javax.swing.JPanel();
        lblValorReserva = new javax.swing.JLabel();
        txtPrecioTotal = new javax.swing.JTextField();
        lblValoreAbonado = new javax.swing.JLabel();
        txtValorAbonado = new javax.swing.JTextField();
        lblValorVuelto = new javax.swing.JLabel();
        txtValorDevolver = new javax.swing.JTextField();
        btnCancelar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(301, 176));

        PanelTitulo.setBackground(new java.awt.Color(222, 222, 237));
        PanelTitulo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        PanelTitulo.setLayout(new java.awt.BorderLayout());

        lblVenta.setBackground(new java.awt.Color(255, 255, 255));
        lblVenta.setFont(new java.awt.Font("Arial", 1, 24));
        lblVenta.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblVenta.setText("Venta");
        lblVenta.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lblVenta.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        PanelTitulo.add(lblVenta, java.awt.BorderLayout.CENTER);

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/pequeñocinema.png"))); // NOI18N
        jLabel8.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        PanelTitulo.add(jLabel8, java.awt.BorderLayout.LINE_START);

        getContentPane().add(PanelTitulo, java.awt.BorderLayout.NORTH);

        PanelContenido.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        PanelContenido.setLayout(new java.awt.GridLayout(4, 3));

        lblValorReserva.setFont(new java.awt.Font("Arial", 0, 11));
        lblValorReserva.setText("Precio Total:");
        PanelContenido.add(lblValorReserva);

        txtPrecioTotal.setFont(new java.awt.Font("Arial", 0, 11));
        txtPrecioTotal.setEnabled(false);
        PanelContenido.add(txtPrecioTotal);

        lblValoreAbonado.setFont(new java.awt.Font("Arial", 0, 11));
        lblValoreAbonado.setText("Valor Abonado:");
        PanelContenido.add(lblValoreAbonado);

        txtValorAbonado.setFont(new java.awt.Font("Arial", 0, 11));
        txtValorAbonado.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtValorAbonadoFocusLost(evt);
            }
        });
        txtValorAbonado.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtValorAbonadoKeyTyped(evt);
            }
        });
        PanelContenido.add(txtValorAbonado);

        lblValorVuelto.setFont(new java.awt.Font("Arial", 0, 11));
        lblValorVuelto.setText("Valor a Devolver:");
        PanelContenido.add(lblValorVuelto);

        txtValorDevolver.setFont(new java.awt.Font("Arial", 0, 11));
        txtValorDevolver.setEnabled(false);
        PanelContenido.add(txtValorDevolver);

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/cancel_icon.jpg"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        PanelContenido.add(btnCancelar);

        btnGuardar.setFont(new java.awt.Font("Arial", 0, 11));
        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/save_icon.jpg"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        PanelContenido.add(btnGuardar);

        getContentPane().add(PanelContenido, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtValorAbonadoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtValorAbonadoKeyTyped

        char c = evt.getKeyChar();

        if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE) ||
         (c == '.'))) 
        {
            getToolkit().beep();
            evt.consume();
        }
    }//GEN-LAST:event_txtValorAbonadoKeyTyped

    private boolean ValidarAbonado()
    {
        return ((txtValorAbonado.getText().length() > 0)
        && (Double.parseDouble(txtValorAbonado.getText())) >= (Double.parseDouble(txtPrecioTotal.getText())));
    }
    
    private void txtValorAbonadoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtValorAbonadoFocusLost

        if (ValidarAbonado())
        {
            txtValorDevolver.setText(String.valueOf(((Double.parseDouble(txtPrecioTotal.getText())) - (Double.parseDouble(txtValorAbonado.getText())))*(-1)));
        }
    }//GEN-LAST:event_txtValorAbonadoFocusLost

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed

        if (ValidarAbonado())
        {
            try
            {
                IBoleteria i = Fabrica.getIBoleteria();

                DTVenta venta = new DTVenta(0, Double.parseDouble(txtValorAbonado.getText()), reserva);

                int result = i.crearVenta(venta);

                if (result > 0)
                {
                    Date date = new Date();
                    List<DTEntrada> entradas = new LinkedList<DTEntrada>();

                    for (DTTiposEntrada tipo: reserva.getTiposEntradas())
                    {

                        if (i.typeOfTipoComun(tipo))
                        {

                            for (int x = 0; x < tipo.getCantidadEntradas(); x++)
                            {
                                DTTiposEntrada tipoAux = i.getTipoComun();
                                tipoAux.setCantidadEntradas(1);
                                DTEntrada e = new DTEntrada(0, tipoAux, date);
                                e.setFuncion(reserva.getFuncion());
                                entradas.add(e);
                            }
                        }

                        if (i.typeOfTipoMenor(tipo))
                        {
                            for (int x = 0; x < tipo.getCantidadEntradas(); x++)
                            {
                                DTTiposEntrada tipoAux = i.getTipoMenor();
                                tipoAux.setCantidadEntradas(1);
                                DTEntrada e = new DTEntrada(0, tipoAux, date);
                                e.setFuncion(reserva.getFuncion());
                                entradas.add(e);
                            }
                        }

                        if (i.typeOfTipoMayor(tipo))
                        {
                            for (int x = 0; x < tipo.getCantidadEntradas(); x++)
                            {
                                DTTiposEntrada tipoAux = i.getTipoMayor();
                                tipoAux.setCantidadEntradas(1);
                                DTEntrada e = new DTEntrada(0, tipoAux, date);
                                e.setFuncion(reserva.getFuncion());
                                entradas.add(e);
                            }
                        }
                    }

                    if (i.crearEntrada(entradas, result) > 0)
                    {
                        JOptionPane.showMessageDialog(null, "El cliente puede pasar a ver su pelicula ", "Exito", JOptionPane.INFORMATION_MESSAGE);
                        this.setVisible(false);
                    }
                    else  JOptionPane.showMessageDialog(null, "Ha ocurrido un error", "Error", JOptionPane.ERROR_MESSAGE);
                }
                else
                    JOptionPane.showMessageDialog(null, "Ocurrio un error y no se pudo realizar la venta", "Error", JOptionPane.ERROR_MESSAGE);
            }
            catch(Exception ex)
            {
                JOptionPane.showMessageDialog(null, ex.getMessage().toString(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        else
          JOptionPane.showMessageDialog(null, "El valor abonado es menor al precio total de las entradas", "Advertencia", JOptionPane.ERROR_MESSAGE);  
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed

        this.setVisible(false);
    }//GEN-LAST:event_btnCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new GenerarEntrada().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel PanelContenido;
    private javax.swing.JPanel PanelTitulo;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel lblValorReserva;
    private javax.swing.JLabel lblValorVuelto;
    private javax.swing.JLabel lblValoreAbonado;
    private javax.swing.JLabel lblVenta;
    private javax.swing.JTextField txtPrecioTotal;
    private javax.swing.JTextField txtValorAbonado;
    private javax.swing.JTextField txtValorDevolver;
    // End of variables declaration//GEN-END:variables
}
